import 'package:flutter_blog_manage_study/http/http_request.dart';
import 'package:flutter_blog_manage_study/http/request.dart';
import 'package:flutter_blog_manage_study/http/request_api.dart';
import 'package:flutter_blog_manage_study/model/user_entity.dart';
import 'package:flutter_blog_manage_study/util/sp/sp_util.dart';

/// * 作者: Tao
/// * 日期: 2024/3/20
/// * 时间: 10:19
/// * 描述: 请求仓库
class RequestRepository {

  /// 注册
  /// * [account] 账号
  /// * [password] 密码
  /// * [rePassword] 确认密码
  /// * [success] 请求成功回调
  /// * [fail] 请求失败回调
  void register(
    String account,
    String password,
    String rePassword, {
    Success<UserEntity>? success,
    Fail? fail,
  }) {
    Request.post<dynamic>(RequestApi.apiRegister, {
      "username": account,
      "password": password,
      "repassword": rePassword
    }, success: (data) {
      var registerInfo = UserEntity.fromJson(data);
      registerInfo.password = password;
      if (success != null) {
        success(registerInfo);
      }
    }, fail: (code, msg) {
      if (fail != null) {
        fail(code, msg);
      }
    });
  }


  /// 登录
  /// * [account] 账号
  /// * [password] 密码
  /// * [success] 请求成功回调
  /// * [fail] 请求失败回调
  void login(
    String account,
    String password, {
    Success<UserEntity>? success,
    Fail? fail,
  }) {
    Request.post<dynamic>(RequestApi.apiLogin, {
      "username": account,
      "password": password,
    }, success: (data) {
      var loginInfo = UserEntity.fromJson(data);
      loginInfo.password = password;
      // 保存用户信息
      SPUtil.putUserInfo(loginInfo);
      if (success != null) {
        success(loginInfo);
      }
    }, fail: (code, msg) {
      if (fail != null) {
        fail(code, msg);
      }
    });
  }
}
